#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
|===== Conference Bot Plugin ============
|= Nick Serv
|===== By: ==============================
|= Patrick Kennedy
|===== Current Version: =================
|= 1.0
|===== Description: =========================================
|= Similar to /nickserv in IRC.
|===== Additional Comments: =================================
|= It capitalizes all names as to prevent CAP abuse and name
|= stealing.
|============================================================"""

import re

from ini import *
from utils import *

def init(bot):
	bot.addCommand("nick", cmd_nick)
	
def unload(bot):
	bot.removeCommand('nick')

def cmd_nick(bot, user, msg):
	"""Use a custom nickname inplace of your username.
Useage: /nick [<command>] <nickname>
Commands:
* list [online|mine] - Displays a list of nicknames and the emails of the user.
* clear - Revert to using your original username.
* reg(ister) - Regesters the nickname to your email.
* unreg(ister) - Unregisters the nickname from your email."""
	
	user = getjid(user)
	if isadmin(user):
		msg = msg.strip()
	else:
		msg = re.sub('[^a-zA-Z0-9\s]+','', msg).lower() #Limits the abuse of capitals and makes it harder to steal names.
	msg = msg.encode('utf-8')
	global inuse
	inuse = None
	if nick.inuse.get(user):
		inuse = nick.inuse.get(user).lower()
	
	if msg:
		global nickcap
		nickcap = None
		#==================
		#= Check for commands that have an optional secondary arg first.
		if 'list' in msg:
			if ' ' in msg:
				msg, cmd = msg.split(' ', 1)
			else:
				cmd = None
			list(bot, user, cmd)
		
		elif msg in ["clear", "clean"]:
			del nick.temp[inuse]
			del nick.inuse[user]
			bot.msg(user, "Your name is now: %s" % user)
			
		elif ' ' in msg:
			cmd, nickname = msg.split(' ', 1)
			
			#Remove any parts after a space.
			if ' ' in nickname:
				nickname = nickname[:nickname.find(' ')]
				
			#Set the capitalized version of the nickname.
			#This is ignored if the user is an Admin.
			nickcap = nickname.capitalize()
			if isadmin(user):
				nickcap = nickname
				
			#Register the nickname to the user.
			if cmd in ["reg","register"]:
				registerNick(bot, user, nickname)
				
			#Release the user's rights to the nickname.
			elif cmd in ["unreg","unregister"]:
				unregisterNick(bot, user, nickname)
			
			else:
				bot.error(user, "The command you're tring use doesn't exist!/nPlnote nicknames can't have spaces.")
			
		else:
			nickcap = msg.capitalize()
			if isadmin(user):
				nickcap = msg
			setNick(bot, user, msg.lower())
		
		
	else:
		bot.msg(user, cmd_nick.__doc__)
	savenicklist()

def list(bot, user, cmd):
	names = []
	if cmd in ['me', 'my', 'mine']:
		names = getRegistered(user)
		bot.sys(user, "Your registered names are:\n%s\nTotal: (%d)" % ('\n'.join(names), len(names)))
	
	elif cmd == 'online':
		for i in nick.inuse.keys():
			name = getdisplayname(i)
			if bot.getJidStatus(getjid(i)).items() != []:
				names.append('%s | %s\n' % (name, i))
		bot.sys(user, 'Names:\n%s \ntotal (%d)' % ("\n".join(names).capitalize(), len(names)))
		
	else:
		for i in nick.inuse.keys():
			name = getdisplayname(i)
			names.append('%s | %s\n' % (name, i))
		bot.sys(user, 'Names:\n%s \ntotal (%d)' % (" ".join(names), len(names)))

def getRegistered(user):
	names = []
	for (name, register) in nick.registered.items():
		if getjid(register) == getjid(user):
			names.append(name)
	return names

	
def checkRegister(bot, user, nickname):
	if nickname in nick.registered.keys() and user != nick.registered[nickname]:
		bot.sys(user, '%s has already regestered: _%s_.' % (nick.registered[nickname], nickcap))
		return 1
	return 0
	
def checkUsage(bot, user, nickname, ):
	if nickname in nick.temp.keys() and user != nick.temp[nickname]:
		bot.sys(user, '%s is already using: _%s_.' % (nick.temp[nickname], nickcap))
		return 1
	return 0
	
def clearNick(bot, user, nickname):
	pass
		
#Set a users nickname, removing temporary listings. 
#Registered nicknames need to be removed with "unregisterNick"
def setNick(bot, user, nickname):
	if len(nickname) > 12:
		nickname = nickname[:13]
		bot.sys(user, 'Your nickname is too long (12+ characters) and will be shortened.')
	if checkRegister(bot, user, nickname) or checkUsage(bot, user, nickname):
		return
	else:
		if inuse:
			del nick.temp[inuse]
		del nick.temp[nickname]
		if nickname not in nick.registered.keys():
			nick.temp[nickname] = user
		nick.inuse[user] = nickcap
		bot.sys(user, 'Congratulations! Your name is now: _%s_' % nickcap)
		#Print a message to the command prompt and message log.
		bot.log("NICK: %s is now using the nickname: %s" % (user, nickcap))
		
def registerNick(bot, user, nickname):
	if checkRegister(bot, user, nickname):
		return
	if len(getRegistered(user)) > 5 and not ismod(user):
		bot.error(user, "I'm sorry, you may only register 5 nicknames.\nPlease use )nick list mine to see the ones you have.")
	else:
		nick.registered[nickname] = user
		setNick(bot, user, nickname)
		bot.sys(user, '_%s_ is now regestered to your email address.' % nickcap)
		#Print a message to the command prompt and message log.
		bot.log("NICK: %s has registered the nickname: %s" % (user, nickcap))
		
def unregisterNick(bot, user, nickname):
	if user != nick.registered[nickname] and not isadmin(user):
		bot.sys(user, "How _*dare*_ you try to steal %s's nickname?!" % nick.nickreg[nickname])
	else:
		del nick.registered[nickname]
		if nickname in nick.temp.keys():
			del nick.temp[inuse]
			del nick.inuse[user]
		bot.sys(user, '_%s_ is now free to use.' % nickcap)
		#Print a message to the command prompt and message log.
		bot.log("NICK: %s has unregistered the nickname: %s" % (user, nickcap))
